#include<iostream>
using namespace std;
#include<unistd.h>
#include<sys/types.h>
#include<string>
#include<sys/wait.h>
#include<stdio.h>

int main()
{
    int pipefd[2] = {0};
    pipe(pipefd);
    
    pid_t id = fork();
    if(id == 0)//子读父写
    {
        close(pipefd[1]);
        while(1)
        {
            sleep(3);
            char buffer[1024] = {0};
            ssize_t ret = read(pipefd[0],buffer,sizeof(buffer) - 1);
            if(ret > 0)
            {
                buffer[ret] = 0;
                cout << buffer << endl;
            }
            else if(ret == 0)
            {
                std::cout << "对端关闭" << std::endl;
                break;
            }
            else
            {
                std::cout << "读取失败" <<std::endl;
            }
        }

        exit(0);
        
    }
    else
    {
        //父
        int cnt = 0;
        close(pipefd[0]);
        while(cnt < 10)
        {
            sleep(3);
            cnt++;
            string str = "wycyyds";
            str += (cnt + '0');
            write(pipefd[1],str.c_str(),str.size());
        }
    }

    pid_t rid = waitpid(id,nullptr,0);
    if(rid > 0)
    {
        std::cout << "回收子进程成功" << std::endl;
    }
    else
    {
        std::cout << "回收子进程失败: ";
        perror("waitpid");
        std::cout << std::endl;
        
    }
    

    return 0;
}